#include "Timers.h"
#include <windows.h>

Timers::Timers()
{
	m_Timers.clear();
	maxID = 0;
};

unsigned int Timers::Create(unsigned int uiInterval, PTIMERFUNC pFunction, char *pParams)
{
	TimerData	td;
	td.pFunc		= pFunction;
	td.pParams		= pParams;
	td.uiInterval	= uiInterval;
	td.uiResiduaryTime = uiInterval;
	td.uiTimerId = GenID();
	m_Timers.push_back(td);
	return td.uiTimerId;
}
void Timers::Start(unsigned int uiID)
{
	std::list<TimerData>::iterator iter= m_Timers.begin();
	//for(unsigned int ui; ui<uiID; ui++, iter++);
	for(; iter!=m_Timers.end(); iter++)
		if (iter->uiTimerId==uiID)
		{
			iter->fPaused=false;
			break;
		}
}
void Timers::Pause(unsigned int uiID)
{
	std::list<TimerData>::iterator iter= m_Timers.begin();
	//for(unsigned int ui; ui<uiID; ui++, iter++);
	for(; iter!=m_Timers.end(); iter++)
		if (iter->uiTimerId==uiID)
		{
			iter->fPaused=true;
			break;
		}
}
void Timers::Delete(unsigned int uiID)
{
	std::list<TimerData>::iterator iter= m_Timers.begin();
	//for(unsigned int ui; ui<uiID; ui++, iter++);
	for(; iter!=m_Timers.end(); iter++)
		if (iter->uiTimerId==uiID)
		{
			m_Timers.erase(iter);
			break;
		}
}
void Timers::UpdateAll(unsigned int uiMilliSeconds)
{
	std::list<TimerData>::iterator iter= m_Timers.begin();
	for(; iter!=m_Timers.end(); iter++)
	{
		if(iter->fPaused == true) return;
		unsigned int uiTime = uiMilliSeconds;
		while(uiTime> iter->uiInterval)
		{
			iter->pFunc(iter->pParams);
			uiTime -= iter->uiInterval;
		}

		if(iter->uiResiduaryTime < uiTime)
		{
			iter->uiResiduaryTime += iter -> uiInterval - uiTime;
			iter->pFunc(iter->pParams);
		}
		else
			iter->uiResiduaryTime -= uiTime;
	}
}

unsigned int Timers::GenID()
{
	this->maxID++;
	return this->maxID-1;
}